<script setup lang="ts">
import { useChannelStore } from '@/stores/channel'
import type { ArticleItem, ArticleResData } from '@/types/data'
import axios from 'axios'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'

const store = useChannelStore()
const list = ref<ArticleItem[]>([])
// 2. 监听
watch(
  // 监听变化的数据
  () => store.channelId,
  // 变化后执行的逻辑
  async () => {
    // 发送请求获取数据
    // 传递查询参数
    const res = await axios.get<ArticleResData>('http://geek.itheima.net/v1_0/articles', {
      params: { channel_id: store.channelId, timestamp: Date.now() },
    })
    console.log(res.data.data.results)
    // 赋值
    list.value = res.data.data.results
  },
  { immediate: true }, // 立即执行， 因为默认是0，不立即执行则不点击不执行
)
const router = useRouter()

// 点击跳转详情页事件
const toDetail = (id: string) => {
  console.log(id)
  router.push({
    path: './detail',
    query: {
      id: id,
    },
  })
}
</script>

<template>
  <div class="article-list">
    <div
      class="article-item"
      v-for="item in list"
      :key="item.art_id"
      @click="toDetail(item.art_id)"
    >
      <p class="title">{{ item.title }}</p>
      <template v-if="item.cover.type > 0">
        <img v-for="(it, index) in item.cover.images" class="img" :src="it" :key="index" alt="" />
      </template>
      <div class="info">
        <span>{{ item.aut_name }}</span>
        <span>{{ item.comm_count }}评论</span>
        <span>{{ item.pubdate }}</span>
      </div>
    </div>
  </div>
</template>
